package com.crm.system.service.impl.followPlanManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contactManager.ContactInformation;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerContactPerson;
import com.crm.model.entity.followPlanManager.CpFollowPlan;
import com.crm.model.entity.reminditem.SysRemindItem;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.followPlanManager.CpFollowPlanQO;
import com.crm.model.vo.contactManager.ContactInformationVO;
import com.crm.model.vo.contactManager.ContactVO;
import com.crm.model.vo.followPlanManager.CpFollowPlanVO;
import com.crm.model.vo.followPlanManager.FollowPlanContactListVO;
import com.crm.model.vo.followPlanManager.FollowPlanCountVO;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contactManager.ContactInformationDbService;
import com.crm.service.customerManager.CustomerContactPersonDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerPoolDbService;
import com.crm.service.followPlanManager.FollowPlanDbService;
import com.crm.service.reminditem.SysRemindItemDbService;
import com.crm.system.service.contactManager.ContactService;
import com.crm.system.service.followPlanManager.FollowPlanService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author: chaifuyou
 * @date 2021/3/31 16:44
 */
@Service
public class FollowPlanServiceImpl implements FollowPlanService {
    @Autowired
    private FollowPlanDbService followPlanDbService;

    @Autowired
    private CustomerDbService customerDbService;

    @Autowired
    ClueFollowDbService clueFollowDbService;

    @Autowired
    CustomerContactPersonDbService customerContactPersonDbService;

    @Autowired
    CustomerPoolDbService customerPoolDbService;

    @Autowired
    ContactInformationDbService contactInformationDbService;

    @Autowired
    ContactDbService contactDbService;

    @Autowired
    ContactService contactService;

    @Autowired
    SysRemindItemDbService sysRemindItemDbService;

    /**
     * 跟进计划列表
     * @return
     */
    @Override
    public DhPageInfo<CpFollowPlanVO> selectFollowPlanList(CpFollowPlanQO cpFollowPlanQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (cpFollowPlanQO.getIsAdmin() == 1){
            if (!CommonUtils.isAdmin(userAccount.getUserId())){
                cpFollowPlanQO.setCompanyId(userAccount.getCompanyId());
            }
        }else if (cpFollowPlanQO.getIsAdmin() == 2){
            cpFollowPlanQO.setAccountId(userAccount.getAccountId());
        }
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                case "planDate":
                {
                    order.append("plan_date ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        Integer dateUnit=getDateUnit(cpFollowPlanQO.getDateType());
        Integer followUnit=getFollowUnit(cpFollowPlanQO.getFollowType());
        List<CpFollowPlanVO> retustList=followPlanDbService.selectCustomerProductList(cpFollowPlanQO,order.toString(),dateUnit,followUnit);
        PageInfo<CpFollowPlanVO> page =new PageInfo(retustList);
        return new DhPageInfo<CpFollowPlanVO>(page,retustList);
    }

    /**
     * 添加跟进计划
     * @param cpFollowPlan
     */
    @Override
    public void addFollowPlan(CpFollowPlan cpFollowPlan) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        Customer customer=customerDbService.selectCustomerById(cpFollowPlan.getCustomerId());
        SysRemindItem sysRemindItem = null;
        //设置提醒
        if ("1".equals(cpFollowPlan.getPlanStatus())){
            sysRemindItem= addRemind(cpFollowPlan,customer);
        }
        if (Objects.nonNull(sysRemindItem)){
            cpFollowPlan.setRemindItemId(sysRemindItem.getRemindItemId());
        }
        //根据客户id、联系人名称和联系方式判重，是否插入客户联系人
        /*CustomerContactPerson customerContactPersons = customerContactPersonDbService.isInsertCustomerContactPerson(
                cpFollowPlan.getCustomerId(), cpFollowPlan.getContactPerson(), cpFollowPlan.getContactPersonPhone());*/
        CustomerContactPerson customerContactPersons = null;
        ContactVO contactVO = contactDbService.isInsertContactPerson(cpFollowPlan.getCustomerId(),cpFollowPlan.getContactPerson(), cpFollowPlan.getContactPersonPhone());
        Contact contact = null;
        if (contactVO == null) {
            //新增客户下的联系人
            customerContactPersons = getCustomerContactPerson(cpFollowPlan, userAccount);
            String customerContactPersonId = customerContactPersons.getCustomerContactPersonId();
            //新增联系人管理的联系人
            contact = getContact(cpFollowPlan, userAccount,customerContactPersonId);
            contactDbService.addContact(contact);
            List<ContactInformationVO> contactInformationList = contactService.getCustomerIdAndContactInformation(cpFollowPlan.getCustomerId(), cpFollowPlan.getContactPersonPhone(), "");
            if (contactInformationList == null || contactInformationList.size() <= 0) {
                //新增联系方式
                ContactInformation contactInformationPOJO = getContactInformation(userAccount,  cpFollowPlan.getContactPersonPhone(), cpFollowPlan.getCustomerId(), contact);
                contactInformationDbService.addContactInformation(contactInformationPOJO);
            }
        }else {
            cpFollowPlan.setContactId(contactVO.getContactId());
        }
        if (Objects.nonNull(contact)){
            cpFollowPlan.setContactId(contact.getContactId());
        }
        cpFollowPlan.setCpFollowPlanId(CommonUtils.getGUID());
        cpFollowPlan.setCreatePeopleId(userAccount.getAccountId());
        cpFollowPlan.setCreateTm(new Date());
        //cpFollowPlan.setContactPerson(customer.getContactPerson());
        //cpFollowPlan.setContactPersonPhone(customer.getContactPersonPhone());
        followPlanDbService.addFollowPlan(cpFollowPlan);
    }

    /**
     * 取消跟进计划
     * @param cpFollowPlanId
     * @return
     *
     * 修改：针对计划进行筛选，已完成计划不允许取消，修改void返回值为boolean
     * 新增参数Integer type，用于判断是否是普通用户，type=1是普通用户
     * @Author renshaorong
     * @Date 2021/5/26
     */
    @Override
    public boolean deleteFollowPlan(String cpFollowPlanId,Integer type) {
        if(type == 1){
            //判断是否存在id为cpFollowPlanId的计划
            CpFollowPlanVO cpFollowPlanVO = followPlanDbService.selectFollowPlanInfoById(cpFollowPlanId);
            if(cpFollowPlanVO == null || "".equals(cpFollowPlanVO)){
                return false;
            }
            //判断是否已完成
            Integer followCount =clueFollowDbService.canBeDelete(cpFollowPlanId);
            if(followCount > 0){//已完成，不可删除
                return false;
            }
            followPlanDbService.deleteFollowPlan(cpFollowPlanId);
            return true;
        }else{
            followPlanDbService.deleteFollowPlan(cpFollowPlanId);
            return true;
        }
    }

    /**
     * 修改跟进计划
     * @param cpFollowPlan
     * @return
     */
    @Override
    public void updateFollowPlan(CpFollowPlan cpFollowPlan) {
        CpFollowPlanVO followPlanVo = followPlanDbService.selectFollowPlanInfoById(cpFollowPlan.getCpFollowPlanId());
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        //根据客户id、联系人名称和联系方式判重，是否插入客户联系人
        CustomerContactPerson customerContactPersons = customerContactPersonDbService.isInsertCustomerContactPerson(
                cpFollowPlan.getCustomerId(), cpFollowPlan.getContactPerson(), cpFollowPlan.getContactPersonPhone());
        if (customerContactPersons == null) {
            //新增客户下的联系人
            customerContactPersons = getCustomerContactPerson(cpFollowPlan, userAccount);
            String customerContactPersonId = customerContactPersons.getCustomerContactPersonId();
            //新增联系人管理的联系人
            Contact contact = getContact(cpFollowPlan, userAccount,customerContactPersonId);
            contactDbService.addContact(contact);
            List<ContactInformationVO> contactInformationList = contactService.getCustomerIdAndContactInformation(cpFollowPlan.getCustomerId(), cpFollowPlan.getContactPersonPhone(), "");
            if (contactInformationList == null || contactInformationList.size() <= 0) {
                //新增联系方式
                ContactInformation contactInformationPOJO = getContactInformation(userAccount,  cpFollowPlan.getContactPersonPhone(), cpFollowPlan.getCustomerId(), contact);
                contactInformationDbService.addContactInformation(contactInformationPOJO);
            }
        }
        Customer customer=customerDbService.selectCustomerById(cpFollowPlan.getCustomerId());
        //cpFollowPlan.setContactPerson(customer.getContactPerson());
        //cpFollowPlan.setContactPersonPhone(customer.getContsys_remind_itemactPersonPhone());
        cpFollowPlan.setUpdatePeopleId(userAccount.getAccountId());
        cpFollowPlan.setUpdateTm(new Date());
        followPlanDbService.updateFollowPlan(cpFollowPlan);
        //删除原来的提醒
        if (Objects.nonNull(followPlanVo.getRemindItemId())){
            sysRemindItemDbService.deleteById(followPlanVo.getRemindItemId(),(short) StatusCodeEnum.DELETE_CODE.getState());
        }
        //设置提醒
        if ("1".equals(cpFollowPlan.getPlanStatus())){
            addRemind(cpFollowPlan,customer);
        }
    }

    /**
     * 设置提醒
     * @param cpFollowPlan
     * @param customer
     */
    public SysRemindItem addRemind(CpFollowPlan cpFollowPlan,Customer customer){
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        SysRemindItem sysRemindItem = new SysRemindItem();
        sysRemindItem.setRemindItemId(CommonUtils.getGUID());
        sysRemindItem.setRemindEvent("跟进客户："+customer.getCustomerName());
        sysRemindItem.setSetTm(cpFollowPlan.getPlanDate());
        sysRemindItem.setCreatePeopleId(userAccount.getAccountId());
        sysRemindItem.setCreateTm(new Date());
        sysRemindItem.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        sysRemindItemDbService.insert(sysRemindItem);
        return sysRemindItem;
    }

    /**
     * 联系方式记录
     * @Author chaifuyou
     * @Date  2021/04/23 16:52
     * @param userAccount --账号信息
     * @param contactInformation --联系方式
     * @param customerId --客户id
     * @param contact --联系人管理表
     * @return {@link {com.crm.model.entity.contactManager.ContactInformation}}
     */
    private ContactInformation getContactInformation(UserAccount userAccount, String contactInformation, String customerId, Contact contact) {
        ContactInformation contactInformationPOJO = new ContactInformation();
        contactInformationPOJO.setContactInformationId(CommonUtils.getGUID());
        contactInformationPOJO.setContactInformation(contactInformation);
        contactInformationPOJO.setContactType("跟进电话");
        contactInformationPOJO.setContactInformationType(0);
        contactInformationPOJO.setCreatePeopleId(userAccount.getAccountId());
        contactInformationPOJO.setCreateTm(new Date());
        contactInformationPOJO.setUpdatePeopleId(userAccount.getAccountId());
        contactInformationPOJO.setUpdateTm(new Date());
        contactInformationPOJO.setContactId(contact.getContactId());
        contactInformationPOJO.setCustomerId(customerId);
        contactInformationPOJO.setAbolishState(1);  //废止状态  1启动 2废止
        contactInformationPOJO.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        return contactInformationPOJO;
    }

    /**
     * 联系人管理表记录
     * @Author chaifuyou
     * @Date  2021/04/23 16:33
     * @param cpFollowPlan --跟进参数
     * @param userAccount  --账号信息
     * @return {@link {com.crm.model.entity.contactManager.Contact}}
     */
    private Contact getContact(CpFollowPlan cpFollowPlan, UserAccount userAccount,String customerContactPersonId) {
        Contact contact = new Contact();
        contact.setContactId(CommonUtils.getGUID());
        contact.setContactName(cpFollowPlan.getContactPerson());
        contact.setContactInformation(cpFollowPlan.getContactPersonPhone());
        contact.setFollowUpTimes(0);
        contact.setCreatePeopleId(userAccount.getAccountId());
        contact.setCreateTm(new Date());
        contact.setUpdatePeopleId(userAccount.getAccountId());
        contact.setUpdateTm(new Date());
        contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //contact.setMergeState(0);
        contact.setContactNature(0);
        contact.setAbolishState(1);
        contact.setCustomerId(cpFollowPlan.getCustomerId());
        contact.setAccountId(userAccount.getAccountId());
        contact.setCompanyId(userAccount.getCompanyId());
        return contact;
    }

    /**
     * 客户联系人记录
     * @Author chaifuyou
     * @Date  2021/04/23 15:22
     * @param cpFollowPlan --跟进参数
     * @param userAccount  --账号信息
     * @return {@link {com.crm.model.entity.customerManager.CustomerContactPerson}}
     */
    public CustomerContactPerson getCustomerContactPerson(CpFollowPlan cpFollowPlan, UserAccount userAccount) {
        CustomerContactPerson customerContactPerson = new CustomerContactPerson();
        customerContactPerson.setCustomerContactPersonId(CommonUtils.getGUID());
        customerContactPerson.setContactName(cpFollowPlan.getContactPerson());
        customerContactPerson.setContactInformation(cpFollowPlan.getContactPersonPhone());
        customerContactPerson.setCreatePeopleId(userAccount.getAccountId());
        customerContactPerson.setCreateTm(new Date());
        customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
        customerContactPerson.setUpdateTm(new Date());
        customerContactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        customerContactPerson.setAbolishState(1);
        customerContactPerson.setMergeState(0);
        customerContactPerson.setCustomerId(cpFollowPlan.getCustomerId());
        //新增客户下的联系人
        customerPoolDbService.addCustomerContactPerson(customerContactPerson);
        return customerContactPerson;
    }

    /**
     * 统计日期的跟进情况
     * @param planDate
     * @return
     */
    @Override
    public FollowPlanCountVO getFollowPlanCount(String planDate,String startDate,String endDate) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        FollowPlanCountVO vo =new FollowPlanCountVO();
        //计划跟进人数
        List<Integer> planCount =followPlanDbService.getFollowPlanCount(planDate,userAccount.getAccountId(),startDate,endDate);
        if (planCount.size() > 0){
            vo.setCustomerCount(planCount);
            //获取日期跟进人数
            List<Integer> followCount =clueFollowDbService.getFollowCountByPlanDate(planDate,userAccount.getAccountId(),startDate,endDate);
            //先把跟进人数赋给完成率，方便后续直接重新赋值
            vo.setRatio(followCount);
            for (int i=0;i<planCount.size();i++){
                if (planCount.get(i) >0){
                    vo.getCustomerCount().set(i,planCount.get(i));
                    vo.getRatio().set(i,followCount.get(i) * 100 / planCount.get(i));
                }else {
                    vo.getCustomerCount().set(i,planCount.get(i));
                    vo.getRatio().set(i,0);
                }
            }
        }
        return vo;
    }

    /**
     * 当天跟进的客户列表
     * @param planDate
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<FollowPlanContactListVO> getFollowPlanListByDate(String planDate, Integer pageIndex, Integer pageSize, String sortName, String sortOrder,String dateType,String customerId) {
        planDate = planDate.replaceAll("-","");
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        Integer dateUnit = getDateUnit(dateType);
        List<FollowPlanContactListVO> list =followPlanDbService.getFollowPlanListByDate(planDate,order,userAccount.getAccountId(),dateUnit);
        List<FollowPlanContactListVO> resultList = list;
        FollowPlanContactListVO vo = new FollowPlanContactListVO();
        //customerId不为空的话需要把前端传过来的customerId的客户排在第一位返回
        if (Objects.nonNull(customerId)){
            for (int i=0;i<list.size();i++){
                //先把第一个客户记录下，便于数据换位置
                if (i == 0){
                    vo = list.get(i);
                }
                //resultList.set(i,list.get(i));
                //customerId匹配上了把customerId的客户放到第一位，原来第一位的放到customerId客户的位置
                if (customerId.equals(list.get(i).getCustomerId())){
                    resultList.set(0,list.get(i));
                    resultList.set(i,vo);
                    break;
                }
            }
        }
        PageInfo<FollowPlanContactListVO> pageInfo=new PageInfo<>(resultList);
        return new DhPageInfo<FollowPlanContactListVO>(pageInfo,resultList);
    }

    /**
     * 日期类型(全部/本周/本月/本年度)
     * @Author chaifuyou
     * @Date  2021/4/1 16:12
     * @param dateType -(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年；thisToday:今天)
     * @return {@link {java.lang.Integer}}
     */
    private Integer getDateUnit(String dateType) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("topWeek".equals(dateType)) {
                //上周
                dateUnit = 5;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
            if ("thisToday".equals(dateType)) {
                //今天
                dateUnit = 4;
            }
        }
        return dateUnit;
    }

    /**
     * @Author chaifuyou
     * @Date  2021/4/1 16:12
     * @param dateType -(followAll:全部跟进; 计划跟进:计划跟进)
     * @return {@link {java.lang.Integer}}
     */
    private Integer getFollowUnit(String dateType) {
        Integer followUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("followAll".equals(dateType)) {
                //全部跟进
                followUnit = 1;
            }
            if ("plan".equals(dateType)) {
                //计划跟进
                followUnit = 2;
            }
        }
        return followUnit;
    }
}
